/* global Cesium viewer */
import dataQueryFunc from '../dataQueryFunc';
import paramManager from './paramManager';
import shp from 'shpjs';

class DrawObj {
    constructor(callFunc) {
        this.callFunc = callFunc ? callFunc : null;
    }
    drawExtent() {
        let drawHelper = new Cesium.C_DrawHelper(viewer.scene);
        drawHelper.enable = true;
        drawHelper.startDrawingExtent(
            {
                fill: false,
                outline: true,
                outlineColor: 'rgba(253, 128, 69, 1.0)',
                outlineWidth: 3,
                enEdit: false,
            },
            {
                startCallback: this.drawStartCallback.bind(this),
                endCallback: this.drawEndCallback.bind(this),
            }
        );
    }

    drawCircle() {
        let drawHelper = new Cesium.C_DrawHelper(viewer.scene);
        drawHelper.enable = true;
        drawHelper.startDrawingCircle(
            {
                fill: false,
                outline: true,
                outlineColor: 'rgba(253, 128, 69, 1.0)',
                outlineWidth: 3,
                enEdit: false,
            },
            {
                startCallback: this.drawStartCallback.bind(this),
                endCallback: this.drawEndCallback.bind(this),
            }
        );
    }
    drawPoint() {
        let drawHelper = new Cesium.C_DrawHelper(viewer.scene);
        drawHelper.enable = true;
        drawHelper.startDrawingMarker(
            {},
            {
                startCallback: this.drawStartCallback.bind(this),
                endCallback: this.drawEndCallback.bind(this),
            }
        );
    }
    drawArea() {
        let drawHelper = new Cesium.C_DrawHelper(viewer.scene);
        drawHelper.enable = true;
        drawHelper.startDrawingPolygon(
            {
                fill: false,
                outline: true,
                outlineColor: 'rgba(253, 128, 69, 1.0)',
                outlineWidth: 3,
                enEdit: false,
            },
            {
                startCallback: this.drawStartCallback.bind(this),
                endCallback: this.drawEndCallback.bind(this),
            }
        );
    }

    // 解析shape文件
    parsingShape(files, fileList) {
        let _self = this;
        new Cesium.C_DrawHelper(viewer.scene).stopDrawing();
        new Cesium.C_DrawHelper(viewer.scene).clearMarker();
        if (fileList) {
            let file = fileList[fileList.length - 1];
            const name = file.name;
            const extension = name.split('.')[1];
            if ('zip' !== extension) {
                this.$message.warning('文件不是zip文件！请重新选择文件');
            } else {
                const reader = new FileReader();
                const fileData = file.raw;
                reader.readAsArrayBuffer(fileData);
                reader.onload = function(e) {
                    shp(e.target.result)
                        .then(function(data) {
                            dataQueryFunc.createAdministrativeDivisions({ jsonObject: data });
                            _self.setLocationName(JSON.stringify(data), 'geojson');
                        })
                        .catch(function() {
                            _self.$message.warning('文件不符合空间数据规范！请重新选择文件');
                        });
                };
            }
        }
    }

    // 清空绘制isInitiative本頁面主動清除，paramTwo查詢全球按鈕的清除
    deleteArea() {
        new Cesium.C_DrawHelper(viewer.scene).clearMarker();
        dataQueryFunc.clearToolArea();
        paramManager.setParam('geoParam', {});
    }
    // 绘制图形结束的回调
    drawEndCallback(primitive, primitives, positions) {
        if (!primitive) {
            return;
        }
        if (primitive.getType() === 'Marker') {
            let lon = primitive.position.lon;
            let lat = primitive.position.lat;
            this.setLocationName(`POINT(${lon} ${lat})`, 'wkt');
            this.drawPoint();
        } else {
            this.callFunc && this.callFunc();
            let degreesArr = primitive.getDegreesBoundary();
            let degrees = this.positionsHandler(degreesArr);
            this.setLocationName(degrees[0], 'wkt');

            positions = primitive.getBoundary();
            let boundingSphere = Cesium.BoundingSphere.fromPoints(positions);
            dataQueryFunc.createTarget(
                boundingSphere.center,
                [...positions, positions[0]],
                boundingSphere.radius,
                'static/img/place.png'
            );
            primitive.destroy();
        }
    }
    positionsHandler(positions) {
        let bool = false;
        for (let i = 1; i < positions.length; ++i) {
            if (Math.abs(positions[i].longitude - positions[i - 1].longitude) > 180) {
                bool = true;
                break;
            }
        }
        if (bool) {
            let ps1 = '';
            let ps2 = '';
            let ps1Arr = [];
            let ps2Arr = [];
            for (let i = 0; i < positions.length; ++i) {
                if (positions[i].longitude > 0) {
                    ps1 += `${positions[i].longitude} ${positions[i].latitude},`;
                    ps2 += `${positions[i].longitude - 360} ${positions[i].latitude},`;
                    ps1Arr.push(positions[i]);
                    ps2Arr.push({
                        longitude: positions[i].longitude - 360,
                        latitude: positions[i].latitude,
                    });
                } else {
                    ps1Arr.push({
                        longitude: positions[i].longitude + 360,
                        latitude: positions[i].latitude,
                    });
                    ps2Arr.push(positions[i]);
                    ps1 += `${positions[i].longitude + 360} ${positions[i].latitude},`;
                    ps2 += `${positions[i].longitude} ${positions[i].latitude},`;
                }
            }
            if (positions[0].longitude > 0) {
                ps1 += `${positions[0].longitude} ${positions[0].latitude}`;
                ps2 += `${positions[0].longitude - 360} ${positions[0].latitude}`;
            } else {
                ps1 += `${positions[0].longitude + 360} ${positions[0].latitude}`;
                ps2 += `${positions[0].longitude} ${positions[0].latitude}`;
            }
            let multiPolygon = `MultiPolygon(((${ps1})),((${ps2})))`;
            return [multiPolygon, [ps1Arr, ps2Arr]];
        }

        let polygon = 'POLYGON((';
        for (let i = 0; i < positions.length; i++) {
            polygon += `${positions[i].longitude} ${positions[i].latitude},`;
        }
        polygon += `${positions[0].longitude} ${positions[0].latitude}))`;
        return [polygon];
    }
    drawStartCallback() {
        dataQueryFunc.clearToolArea();
    }
    setLocationName(polygon, typeStr) {
        if (!polygon) {
            return;
        }
        paramManager.setParam('geoParam', {
            geo: polygon,
            geoType: typeStr,
        });
    }
}
export default DrawObj;
